import java.util.*;

/**
 * 49. 字母异位词分组
 * https://leetcode-cn.com/problems/group-anagrams/
 */
public class Solutions_49 {
    public static void main(String[] args) {
        String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
        // output: {{"ate","eat","tea"}, {"nat","tan"}, {"bat"}}

        List<List<String>> result = groupAnagrams(strs);
        System.out.println(result);
    }

    public static List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> res = new ArrayList<>();
        if (strs == null || strs.length < 1) {
            return res;
        }
        Map<String, List<String>> map = new HashMap<>();

        // 排序后，字符串相等的，就是异位词
        for (String str : strs) {
            char[] arr = str.toCharArray();
            Arrays.sort(arr);
            String sortStr = String.valueOf(arr);
            if (!map.containsKey(sortStr)) {
                // 遍历 str 前，没有存在的异位词
                map.put(sortStr, new ArrayList<>());
            }
            // 添加到一致的异位词列表中
            map.get(sortStr).add(str);
        }
        for (String str : map.keySet()) {
            res.add(map.get(str));
        }
        return res;
    }
}
